package com.jar.netty_demo.Netty.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

public class NettyServer {
    public static void main(String[] args) {
        /*
         1、创建BossGroup 和 WorkerGroup 实际是两个独立的 Reactor线程池
         2、bossGroup 只处理连接请求，真正的和客户端业务处理，会交给workerGroup完成
         3、两个都是无限循环
         */
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //创建服务器端的启动对象，配置参数
            ServerBootstrap bootstrap = new ServerBootstrap();
            //服务端启动，接受新连接，打印客户端传来的数据
            bootstrap.group(bossGroup, workerGroup) // 设置两个线程组
                    .channel(NioServerSocketChannel.class) // 使用NioServerSocketChannel 作为服务器的通道实现
                    .option(ChannelOption.SO_BACKLOG, 128) // 设置线程队列得到连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new WebSocketChannelInitializer());
            System.out.println("websocket服务已经启动*************************");
            //绑定一个端口，并且同步，生成了一个channelFuture对象
            ChannelFuture channelFuture = bootstrap.bind(new InetSocketAddress(7000)).sync();
            //对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
